package com.ao.andou.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;

import com.ao.andou.R;
import com.ao.andou.common.DrawableHelper;
import com.ao.andou.common.UserHelper;

/**
 * Friend activity
 * 
 * @author debug
 * 
 */
public class FriendActivity extends Activity {
    private ListView friendListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_layout);
        friendListView = (ListView) findViewById(R.id.friend_list);
        new FrendLoadTask().execute();
    }

    private class FrendLoadTask extends AsyncTask<Void, Void, SimpleAdapter> {

        @Override
        protected SimpleAdapter doInBackground(Void... params) {
            // TODO get friends ID from current user
            String[] friendIds = { "pentiumao", "debug1984"};
            ArrayList<HashMap<String, Object>> friends = 
                new ArrayList<HashMap<String, Object>>(friendIds.length);

            for (String friendId : friendIds) {
                HashMap<String, Object> item = UserHelper.findUser(friendId);
                item.put(UserHelper.ICON, 
                        DrawableHelper.getDrawableFromUrl((String) item.get(UserHelper.ICON)));
                friends.add(item);
            }
            return new SimpleAdapter(getApplicationContext(), 
                    friends, R.layout.friend_list_item_layout, 
                    new String[] { UserHelper.TITLE, UserHelper.CONTENT, UserHelper.ICON }, 
                    new int[] { R.id.user_name, R.id.user_signature, R.id.user_icon });
        }

        @Override
        protected void onPostExecute(SimpleAdapter result) {
            result.setViewBinder(mViewBinder);
            friendListView.setAdapter(result);
        }

    }
    
    /*
     * Bind drawable to ImageView
     */
    private ViewBinder mViewBinder = new ViewBinder(){

        public boolean setViewValue(View view, Object data, String textRepresentation) {

            if (view instanceof ImageView) {
                if (data instanceof Drawable) {
                    if(data == null) {
                        // use default user icon
                        ((ImageView) view).setImageResource(R.drawable.icon_user_header);
                    } else {
                        ((ImageView) view).setImageDrawable((Drawable) data);
                    }
                }
            } else {
                return false;
            }
            return true;
        }
    };
    
}
